// 1-返回的是一个Promise实例！
// 2-接收一个对象（配置对象）config
function ajax({method = 'get', url, params, data} = {}) {
	return new Promise(function (resolve, reject) {
		// params是否有值
		if (params) {
			// {a=1,b=2}====>a=1&b=2
			url += "?" + Object.keys(params).map(key => key + "=" + params[key]).join("&");
		}
		const xhr = new XMLHttpRequest();
		xhr.responseType = "json";
		xhr.open(method, url);
		if (data && method === "post") {
			if (typeof data === "object") {
				xhr.setRequestHeader("Content-Type", "application/json");
				xhr.send(JSON.stringify(data))
			} else {
				xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xhr.send(data);
			}
		} else
			xhr.send();
		xhr.onload = function () {
			resolve(xhr.response);
		}
	})
	
}

ajax.get = function (url, config) {
	return this({
		url,
		...config
	})
}

ajax.post = function(url,data,config={}){
	return this({
		url,
		method:"post",
		data,
		...config
	})
}